package com.b2c.erp.controller.fahuo;

import com.alibaba.fastjson.JSON;
import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.vo.order.OrderWaitSendListVo;
import com.b2c.erp.DataConfigObject;
import com.b2c.entity.ErpStockOutPickVo;
import com.b2c.erp.req.GoodsSearchReq;
import com.b2c.erp.req.IdRequest;
import com.b2c.interfaces.erp.ErpOrderService;
import com.b2c.entity.erp.enums.StockOutFormStatusEnum;
import com.b2c.entity.erp.vo.ErpStockOutGoodsListVo;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.interfaces.wms.ErpStockOutFormService;
import com.b2c.entity.enums.EnumErpOrderSendStatus;
import com.b2c.erp.response.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述：
 * 商品出库
 *
 * @author qlp
 * @date 2019-05-31 14:57
 */
@RequestMapping(value = "/ajax_stock_out")
@RestController
public class AjaxStockOutController {
    @Autowired
    private ErpStockOutFormService stockOutGoodsService;

    @Autowired
    private ErpUserActionLogService logService;
    @Autowired
    private ErpOrderService orderService;
    private Logger log = LoggerFactory.getLogger(AjaxStockOutController.class);


    /**
     * 打印拣货单，更新拣货单为已打印
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/print_picking", method = RequestMethod.POST)
    public ApiResult<Integer> printPicking(@RequestBody IdRequest req) {
        if (req.getId() == null)
            return new ApiResult<>(400, "参数错误");

        stockOutGoodsService.printPicking(req.getId());

        return new ApiResult<>(0, "SUCCESS");
    }

    /**
     * 订单确认出库（按订单ID）
     * 更新：2021-07-06 拣货完成直接出库，状态直接变更为已出库
     *
     * @return
     */
    @RequestMapping(value = "/order_stock_out_confirm", method = RequestMethod.POST)
    public ApiResult<Integer> completePicking(HttpServletRequest request,@RequestBody IdRequest req) {
        Long orderId = req.getId();//出库订单ID
        if (orderId == null || orderId == 0)
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少orderId");

//        if(true) return new ApiResult<>(0, "SUCCESS");

        log.info("确认拣货出库,数据确认完成，开始处理出库............");
        Integer userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
        String userName = request.getSession().getAttribute("trueName").toString();

        PagingResponse<OrderWaitSendListVo> results = orderService.getWaitSendOrderList(0,500, EnumErpOrderSendStatus.Picking, null, null, null, 0,0,null,null);
        for(var obj:results.getList()){
            var result = stockOutGoodsService.orderGoodsStockOut(obj.getId(),userId,userName);
            log.info("确认拣货出库完成，订单ID"+orderId+"，处理结果："+ JSON.toJSONString(result));

/*          if(result.getCode() == EnumResultVo.SUCCESS.getIndex()){

                return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "SUCCESS"); //210704-605552681883292
            }else
                return new ApiResult<>(result.getCode(), result.getMsg());*/
        }
        return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "成功");

    }

    /**
     * 根据拣货单号获取拣货商品list
     *
     * @param req ErpInvoicePicking number
     * @return
     */
    @RequestMapping(value = "/get_picking_goods_by_no", method = RequestMethod.POST)
    public ApiResult<List<ErpStockOutGoodsListVo>> getPickingGoods(@RequestBody GoodsSearchReq req) {
        if (StringUtils.isEmpty(req.getKey()))
            return new ApiResult<>(400, "参数错误");

        var pick = stockOutGoodsService.getStockOutFormByNumber(req.getKey());
        if (pick == null) return new ApiResult<>(404, "没找到数据");

        var goods = stockOutGoodsService.getStockOutGoodsForOrderByFormId(pick.getId());
        return new ApiResult<>(0, "SUCCESS", goods);
    }


    /**
     * 确认拣货，更新拣货单为已拣货,（仓库出库）
     *
     * @return
     */
    @RequestMapping(value = "/complete_picking", method = RequestMethod.POST)
    public ApiResult<Integer> completePicking(HttpServletRequest request) {
        log.info("确认拣货开始..............................");
        if (StringUtils.isEmpty(request.getParameter("stockOutFormId")))
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少拣货单id");
        Long stockOutFormId = 0l;
        try {
            stockOutFormId = Long.parseLong(request.getParameter("stockOutFormId"));
        } catch (Exception e) {
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少拣货单id");
        }

        var pick = stockOutGoodsService.getStockOutFormById(stockOutFormId);
        if (pick == null) return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "没找到拣货单");

        if (pick.getStatus().intValue() != StockOutFormStatusEnum.Packing.getIndex())
            return new ApiResult<>(EnumResultVo.DataError.getIndex(), "拣货单状态不正确，不能继续操作");


//        String[] orderItemId = request.getParameterValues("orderItemId");
//        if (orderItemId == null || orderItemId.length == 0)
//            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少必要参数");
//        int totalOrderItem = orderItemId.length;

//        String[] goodsId = request.getParameterValues("goodsId");
//        if (goodsId == null || goodsId.length ==0)
//            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少必要参数");

        String[] skuId = request.getParameterValues("skuId");
        if (skuId == null || skuId.length ==0)
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少必要参数skuId");

//        String[] quantity = request.getParameterValues("quantity");
//        if (quantity == null || quantity.length < totalOrderItem)
//            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少必要参数");
        String[] quantity = request.getParameterValues("quantity");//需要出库的数量
        String[] currQty = request.getParameterValues("currQty");
        if (currQty == null || currQty.length < skuId.length)
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少必要参数currQty");


        String[] shelfId = request.getParameterValues("shelfId");
        if (shelfId == null || shelfId.length < skuId.length)
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少必要参数:仓位信息");

        String[] goodsId = request.getParameterValues("goodsId");
        String[] specNumber=request.getParameterValues("specNumber");
//        if (specNumber == null || specNumber.length < totalOrderItem)
//            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少必要参数");

        //组合出库orderItem数据
        List<ErpStockOutPickVo> list = new ArrayList<>();
        for (int i = 0; i < skuId.length; i++) {
            try {
                ErpStockOutPickVo vo = new ErpStockOutPickVo();
//                vo.setOrderItemId(Long.parseLong(orderItemId[i]));
                vo.setGoodsId(Long.parseLong(goodsId[i]));
                vo.setSkuId(Long.parseLong(skuId[i]));


                Long number = Long.parseLong(currQty[i]);
                if(number.longValue() <= 0){
                    return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少必要参数:"+specNumber[i]+"不能拣货0件");
                }
                if(number.longValue() != Long.parseLong(quantity[i])){
                    return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "缺少必要参数:"+specNumber[i]+"已拣货数量和需要拣货数量不一致");
                }


                //判断当前库存
//                Long currentQty = stockOutGoodsService.getQuantityByStockInfoId(Integer.parseInt(skuId[i]),Integer.parseInt(shelfId[i]));
//                if(number > currentQty)return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), specNumber[i]+"该仓位商品可用库存不足，无法出库");

                vo.setQuantity(number);
                vo.setLocationId(Integer.parseInt(shelfId[i]));

                list.add(vo);

            } catch (Exception e) {
                return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数转换出错");
            }
        }


        try {
            log.info("确认拣货参数组合完成。拣货单ID："+pick.getId()+"，拣货数据："+JSON.toJSONString(list));
            //更新拣货状态
            int result = stockOutGoodsService.completePicking(pick.getId(), list, DataConfigObject.getInstance().getLoginUserId(), DataConfigObject.getInstance().getLoginUserName());

            if (result == -404) {
                return new ApiResult<>(EnumResultVo.NotFound.getIndex(), "拣货单不存在");
            } else if (result == -405) {
                return new ApiResult<>(EnumResultVo.DataError.getIndex(), "拣货仓位数据错误");
            } else if (result == -406) {
                return new ApiResult<>(EnumResultVo.DataError.getIndex(), "仓位可用库存不足");
            } else if (result == -407) {
                return new ApiResult<>(EnumResultVo.DataError.getIndex(), "仓位库存信息不存在");
            }
            else if (result == -500) {
                return new ApiResult<>(EnumResultVo.SystemException.getIndex(), "系统异常，也许是订单数据错误");
            }
            else if (result == 1) {
//                //添加系统日志
//                logService.addUserAction(userId, EnumUserActionType.StockOperation,
//                        "/ajax_stock_out/complete_picking","拣货完成，拣货单Id : "+stockOutFormId+", 日期 : "+new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()),"成功");

                return new ApiResult<>(0, "SUCCESS");
            } else
                return new ApiResult<>(EnumResultVo.SystemException.getIndex(), "未知错误");
        }catch (Exception e){
            return new ApiResult<>(EnumResultVo.SystemException.getIndex(), e.getMessage());
        }

//        if (StringUtils.isEmpty(request.getKey()))
//            return new ApiResult<>(400, "参数错误");
//
//        var pick = stockOutGoodsService.getStockOutFormByNumber(request.getKey());
//        if (pick == null) return new ApiResult<>(404, "没找到数据");
//        if (pick.getStatus().intValue() == StockOutFormStatusEnum.Packing.getIndex()) {
//            //更新拣货状态
//            stockOutGoodsService.completePicking(pick.getId());
//        }

    }
}
